package com.lc.websocket;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 * @author 逝兮诚
 * @date 2017年5月25日 上午9:21:20
 * websocket 服务端
 */
@ServerEndpoint(value = "/websocket")
public class PushService {

	// 连接人数
	private static int count;

	private static CopyOnWriteArraySet<PushService> set = new CopyOnWriteArraySet<>();

	// 服务端与客户端的通话
	private Session session;

	@OnOpen
	public void onOpen(Session session) {
		this.session = session;
		set.add(this);
		addOnlineCount();
		System.out.println("服务器在线人数：" + getOnlineCount());
	}

	@OnClose
	public void onClose(Session session) {
		set.remove(this);
		subOnlineCount();
		System.out.println("服务器在线人数：" + getOnlineCount());
	}

	@OnMessage
	public void onMessage(String message, Session session) {
		System.out.println("来自客户端的消息:" + message);
		// 群发消息
		for (PushService socket : set) {
			try {
				System.out.println(socket.hashCode());
				socket.sendMsg(message);
			} catch (IOException e) {
				e.printStackTrace();
				continue;
			}
		}
	}

	@OnError
	public void onError(Session session, Throwable error) {
		System.out.println("发生错误");
		error.printStackTrace();
	}

	/**
	 * 某个连接发送消息
	 * @param msg
	 */
	public void sendMsg(String msg) throws IOException {
		this.session.getBasicRemote().sendText(msg);
	}

	public static int getOnlineCount() {
		return count;
	}

	public static void addOnlineCount() {
		count++;
	}

	public static void subOnlineCount() {
		count--;
	}
}
